package org.groupg.project;

import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.dsl.Disruptor;
import com.lmax.disruptor.util.DaemonThreadFactory;

// 定义事件类
class LongEvent {
    private long value;

    public void set(long value) {
        this.value = value;
    }

    public long get() {
        return value;
    }
}

// 定义事件工厂
class LongEventFactory implements com.lmax.disruptor.EventFactory<LongEvent> {
    @Override
    public LongEvent newInstance() {
        return new LongEvent();
    }
}

// 定义事件处理器
class LongEventHandler implements com.lmax.disruptor.EventHandler<LongEvent> {
    @Override
    public void onEvent(LongEvent event, long sequence, boolean endOfBatch) {
        System.out.println("Event: " + event.get());
    }
}

public class DisruptorExample1 {
    public static void main(String[] args) throws InterruptedException {
        // 定义 Ring Buffer 大小（必须是 2 的幂）
        int bufferSize = 1024;

        // 创建 Disruptor
        Disruptor<LongEvent> disruptor = new Disruptor<>(
                new LongEventFactory(), bufferSize, DaemonThreadFactory.INSTANCE);

        // 注册事件处理器
        disruptor.handleEventsWith(new LongEventHandler());

        // 启动 Disruptor
        disruptor.start();

        // 获取 Ring Buffer
        RingBuffer<LongEvent> ringBuffer = disruptor.getRingBuffer();

        // 发布事件
        for (long i = 0; i < 10; i++) {
            long sequence = ringBuffer.next(); // 获取下一个可用的序列号
            try {
                LongEvent event = ringBuffer.get(sequence); // 获取事件对象
                event.set(i); // 设置事件数据
            } finally {
                ringBuffer.publish(sequence); // 发布事件
            }
        }

        // 关闭 Disruptor
        disruptor.shutdown();
    }
}